#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8888
#define BUF_SIZE 1024

int main()
{
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    char buffer[BUF_SIZE];
    socklen_t addr_len = sizeof(client_addr);

    // 1. 创建 socket
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(server_fd < 0)
    {
        perror("socket_failed");
        exit(1);
    }

     // 2. 绑定地址
     server_addr.sin_family = AF_INET;
     server_addr.sin_port = htons(PORT);
     server_addr.sin_addr.s_addr = INADDR_ANY;// 监听本机所有 IP
     if(bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
     {
         perror("bind failed");
         close(server_fd);
         exit(1);
     }

     // 3. 监听连接
     if(listen(server_fd, 5) < 0)
     {
         perror("listen failed");
         close(server_fd);
         exit(1);
     }

     printf("Server is listening on port %d...\n", PORT);

     // 4. 接受客户端连接
     client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
     if(client_fd < 0)
     {
         perror("accept failed");
         close(server_fd);
         exit(1);
     }

     // 5. 接收数据
     memset(buffer, 0, sizeof(buffer));
     int len = recv(client_fd, buffer, BUF_SIZE - 1, 0);
     if(len < 0)
     {
          perror("recv failed");
     }
     else
     {
        printf("Received from client: %s\n", buffer);
     }

     // 6. 关闭连接
     close(client_fd);
     close(server_fd);
     return 0;
}


